<?php

/**
 * This is the model class for table "{{member}}".
 *
 * The followings are the available columns in table '{{member}}':
 * @property string $UserID
 * @property string $Email
 * @property string $Phone
 * @property string $UserName
 * @property string $AddTime
 * @property string $Money
 * @property string $FreezeMoney
 * @property integer $Status
 * @property integer $Type
 * @property string $WangWang
 * @property integer $UpdateTime
 * @property string $Nickname
 */
class MemberModel extends BaseModel
{
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{member}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		//后台修改 与  增加都不需要验证
		//商家 新增
		//商家 修改
		//买家 新增
		//买家 修改
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('Email, Phone, UserName, Type, WangWang, Password', 'required', 'on' => 'front_seller'),

			array('UserName', 'length', 'min' => 6),
			//array('UserName',  'match','pattern'=>'/[a-z 0-9 @ .]/i'),
			array('UserName', 'unique'),
			array('Email, Phone, WangWang', 'unique', 'on' => 'front_seller'),
			array('Email', 'email', 'on' => 'front_seller'),
			array('Birthday,Gender,Nickname,WangWang', 'safe'),
			array('Phone','match','pattern'=>'/^1[34578][0-9]{9}$/','message'=>'手机格式不正确', 'on' => 'front_seller'),


			//username验证通过了那email,phone两个至少会有一个为非空，因为username为这两个的其中一个
			array('UserName, Password,Type', 'required', 'on' => 'front_buyers'),
			array('Email', 'email', 'allowEmpty'=>true, 'on' => 'front_buyers'),
			array('Phone','match','pattern'=>'/^1[34578][0-9]{9}$/','allowEmpty'=>true, 'message'=>'手机格式不正确', 'on' => 'front_buyers'),
			array('Email,Phone', 'unique', 'allowEmpty'=>true, 'on' => 'front_buyers'),

			array('Password', 'length', 'tooShort' => '密码不能低于6位！', 'min' => 6),

			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('Email, Phone, UserName, AddTime, Money, FreezeMoney, Status, Type, WangWang, UpdateTime, Nickname,RegisterType', 'safe', 'on'=>'admin'),
			array('UserID, Email, Phone, UserName, AddTime, Money, FreezeMoney, Status, Type, WangWang, UpdateTime, Nickname', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * 用户修改密码
	 * @return [type] [description]
	 */
	public function updatePassword($oldPassword, $newPassword, $newPasswordPwd){
		if($oldPassword && $newPassword && $newPasswordPwd){
			if($newPassword != $newPasswordPwd){
				$this->addError('', '两次密码不一致');
				return false;
			}			
		}else if(!$oldPassword && !$newPassword && !$newPasswordPwd){
			return true;
		}else{
			$this->addError('', '密码需要输入');
			return false;
		}
		return true;
	}



	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'UserID' => '会员ID',
			'Email' => '邮箱',
			'Phone' => '手机',
			'UserName' => '会员名',
			'AddTime' => '注册时间',
			'Money' => '金额',
			'FreezeMoney' => '冻结额',
			'Status' => '状态',
			'Type' => '会员类型',
			'WangWang' => '旺旺',
			'UpdateTime' => '修改时间',
			'Nickname' => '昵称',
			'RegisterType' => '注册状态',
			'LastLoginIP' => '登录IP',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('UserID',$this->UserID,true);
		$criteria->compare('Email',$this->Email,true);
		$criteria->compare('Phone',$this->Phone,true);
		$criteria->compare('UserName',$this->UserName,true);
		$criteria->compare('AddTime',$this->AddTime,true);
		$criteria->compare('Money',$this->Money,true);
		$criteria->compare('FreezeMoney',$this->FreezeMoney,true);
		$criteria->compare('Status',$this->Status);
		$criteria->compare('Type',$this->Type);
		$criteria->compare('WangWang',$this->WangWang,true);
		$criteria->compare('UpdateTime',$this->UpdateTime);
		$criteria->compare('Nickname',$this->Nickname,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
	public function createSearchCriteria()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		if(!empty($_GET['add_start_time'])){
			$add_start_time = strtotime($_GET['add_start_time']);
			$criteria->addCondition('AddTime >= ' . $add_start_time);
		}
		if(!empty($_GET['add_end_time'])){
			$add_end_time = strtotime($_GET['add_end_time']) + 86400;
			$criteria->addCondition('AddTime <= ' . $add_end_time);
		}


		if(!empty($_GET['add_login_time'])){
			$add_login_time = strtotime($_GET['add_login_time']);
			$criteria->addCondition('LatLoginTime >= ' . $add_login_time);
		}
		if(!empty($_GET['end_login_time'])){
			$end_login_time = strtotime($_GET['end_login_time']) + 86400;
			$criteria->addCondition('LatLoginTime <= ' . $end_login_time);
		}


		$criteria->compare('UserID',$this->UserID,true);
		$criteria->compare('Email',$this->Email,true);
		$criteria->compare('Phone',$this->Phone,true);
		$criteria->compare('UserName',$this->UserName,true);
		$criteria->compare('AddTime',$this->AddTime,true);
		$criteria->compare('Money',$this->Money,true);
		$criteria->compare('FreezeMoney',$this->FreezeMoney,true);
		$criteria->compare('Status',$this->Status);
		$criteria->compare('Type',$this->Type);
		$criteria->compare('WangWang',$this->WangWang,true);
		$criteria->compare('UpdateTime',$this->UpdateTime);
		$criteria->compare('Nickname',$this->Nickname,true);

		return 	$criteria;	
	}
	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return MemberModel the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	public function beforeSave(){

		/**
		 * 如果是后台人员操作则可直接修改密码
		 */
		if(!$this->isNewRecord && GROUP_NAME == 'admin'){
			if(!empty($_POST['MemberModel']['Password'])){
				$this->Password = self::encrypt($_POST['MemberModel']['Password']);
			}else{
				$this->Password = self::model()->findByPk($this->UserID)->Password;
			}
		}

		if($this->isNewRecord){
			$this->AddTime = time();
			if(GROUP_NAME == 'admin'){  //后台操作直接状态为1
				$this->Status = 1;
			}else{
				if(!empty($this->Phone)){
					$this->Status = 1;  //买家如果用手机注册则已经验证了
				}else{
					$this->Status = 0;
				}
			}
			$this->Password = self::encrypt($this->Password);
			$this->Ip = Tool::getForwardedForIp();
		}else{
			//修改的时候如果金额有发生变动,则生成金额变动记录
			$model = $this->findByPk($this->UserID);
			if($this->Password != $model->Password){
				$this->Password = self::encrypt($this->Password);
			}			
			if(($model->Money != $this->Money) || ($model->FreezeMoney != $this->FreezeMoney)){
				$model = new MemberMoneyChangeModel();
				$data = array(
					'UserID' => yii::app()->user->ID,
					'UserName' => yii::app()->user->UserName,
					'OldMoney' => $model->Money,
					'Money' => $this->Money,
					'OldFreezeMoney' => $model->FreezeMoney,
					'FreezeMoney' => $this->FreezeMoney,
				);
				$model->save(false);
			}			
		}
		return true;
	}


	public static function encrypt($password){
		return md5($password);
	}

	/**
	 * [sendEmail description]
	 * @param  boolean $isVerification 是否需要去库里面验证是否有发过，且时间是否已经过
	 * @return [type]                  [description]
	 */
	public  static function sendEmail($email, $isVerification = true){		
        if ($isVerification && $model = MemberVerificationModel::getOneData($email) && TIME_TIME-$model->AddTime <= 120) {
            $interval = 120 - TIME_TIME + $model->AddTime;
            yii::app()->user->setFlash("亲，您刚发送了一封邮件，请耐心等待！{$interval}秒后，还没收到请重发！");
            return false;
        }


        $mail = Yii::createComponent('application.extensions.mailer.EMailer');
        $ConfigModel = new ConfigModel();
        $config = $ConfigModel->getConfig();
        $emailTitle = '亲爱的' . $config['sitename'] . '用户   ' . $email . "，请激活您的邮箱，完成注册";
        $code = substr(md5(uniqid(mt_rand(), true)), 0, 32);
        $url = yii::app()->createUrl("/user/user/verify", array('confirmation_token' => $code));
        $emailBody = '
            <table width="720" border="0" cellspacing="0" cellpadding="0">
                      <tbody><tr>
                        <td height="40" style="line-height:24px">亲爱的<a href="mailto:' . $email  . '" target="_blank">' . $email  . '</a>：</td>
                      </tr>
                      <tr>
                        <td style="line-height:24px">感谢注册' . $config['sitename'] . '会员！<br>
                          请点击链接激活账号（链接48小时内有效）：<br>
                          <a href="' . Yii::app()->request->hostInfo . $url . '" target="_blank">' . Yii::app()->request->hostInfo . $url . '</a>
                          <br>
                          如果您的邮箱不支持链接点击，请将以上链接地址拷贝到您的浏览器地址栏中。<br>
                          如果您没有申请注册' . $config['sitename'] . '，请忽略此邮件
                        </td>
                      </tr>
                      <tr>
                        <td align="right" height="30">' . $config['sitename'] . '</td>
                      </tr>
                      <tr>
                        <td align="right"><span times="" t="5" style="border-bottom: 1px dashed rgb(204, 204, 204);">' . date('Y-m-d', time()) . '</span></td>
                      </tr>
                      <tr>
                        <td valign="middle" align="center" height="40" style="color:#999">（本邮件由系统自动发出，请勿回复。）</td>
                      </tr>
                    </tbody>
            </table>
            ';
        if ($mail->sendEmail($email, $emailTitle, $emailBody)) {
        	MemberVerificationModel::saveData(array('Code' => $code, 'Email' => $email));
            return true;
        }
        yii::app()->user->setFlash("邮件发送失败");
        return false;		
	}

    /**
     * 获取用户基本表信息
     * @param type $identifier 用户名/用户UID
     * @return boolean
     */
    public function getUserInfo($identifier) {
        $where = array();
        //检测是否为uid登录方式
        if (is_int($identifier)) {
            return self::getOneDataForUserID($identifier);
        } else {
        	$model = self::model()->find(BaseModel::getC(array('UserName' => $identifier)));
        	if($model){
            	return $model->attributes;
        	}else{
        		return array();
        	}
        }
    }
	/**
	 * 状态
	 * @return [type] [description]
	 */
	public static function getTypeHtml($mixData = false){
		$arrData = array(
			0 => '买家会员',
			1 => '商家会员',			
		);
		if($mixData !== false){
			return $arrData[$mixData];
		}else{
			return $arrData;
		}
	}

	/**
	 * 状态
	 * @return [type] [description]
	 */
	public static function getStatusHtml($mixData = false){
		$arrData = array(
			0 => '未验证',
			1 => '已验证',			
		);
		if($mixData !== false){
			return $arrData[$mixData];
		}else{
			return $arrData;
		}
	}
	/**
	 * 通过userid获取用户信息
	 * @return [type] [description]
	 */
	public static function getOneDataForUserID($UserID, $bloIsCache = true){
		$strKey = "MemberModel_getOneDataForUserID" . $UserID;
		$arrCache = yii::app()->cache->get($strKey);
        if($bloIsCache && $arrCache !== false){
            return $arrCache;
        }

        $arrCache = array();
        $objModels = self::model()->findByPk($UserID);
        $arrCache = $objModels->attributes;
        
        yii::app()->cache->set($strKey, $arrCache, 600);
        return $arrCache;	
	}

	public function afterSave(){
		self::getOneDataForUserID($this->UserID,false);
	}

	public function afterDelete(){
		self::getOneDataForUserID($this->UserID,false);
	}

	/**
	 * 状态
	 * @return [type] [description]
	 */
	public static function getGenderHtml($mixData = false){
		$arrData = array(
			//0 => '空',
			1 => '男',
			2 => '女',				
		);
		if($mixData !== false){
			return $arrData[$mixData];
		}else{
			return $arrData;
		}
	}


}
